<template> 
    <Modal
        :value="visible"
        :title="title"
        width="700"
        @on-cancel="handleCancel"
        @on-ok="submit" >
          <div class="modalWrap">
            <div class="title">客户基本信息</div>  
            <Form :label-width="100" class="editDomain" ref="form"  :model="temp" :rules="ruleValidate">
                <!-- <Row v-if="isCreate">
                    <Col span="22">
                    <FormItem label="客户："> 
                        <Select filterable v-model="temp.customer_id" clearable placeholder="请选择" style="width: 400px;">
                            <Option v-for="(item,index) in allCustomers" :value="item.customer_id" :key="index">{{item.customer_mark}}</Option>
                        </Select>   
                    </FormItem>
                    </Col>
                    <Col span="4"></Col>
                </Row> -->
                <Row>
                    <Col span="22">
                    <FormItem label="域名：" prop="domain_id"> 
                        <!-- <Select filterable v-if="isCreate" v-model="temp.domain_id" placeholder="请选择" style="width: 400px;">
                            <Option v-for="(item,index) in customerRelatedomains" :value="`${item.id}`" :key="index">{{item.domain}}</Option>
                        </Select>  -->
                        <!-- <span v-if="!isCreate"> -->
                        <span>
                            {{domainName}}
                        </span>
                    </FormItem>
                    </Col>
                    <Col span="4"></Col>
                </Row>  
            </Form>
            <div class="title" :style="{color: info ? '#333' : 'red'}">
                交换机 
                <span :style="{fontSize:'12px', color: info ? '#999' : 'red'}">(host、community必填且格式正确)</span>
            </div>
            <div class="ivu-table-wrapper modal-table">
                <table class="ivu-table ivu-table-small" style="width: 100%;">
                    <thead class="ivu-table-header">
                        <th>host</th> 
                        <th>community</th> 
                        <th>汇聚口<span style="color: #999; font-size: 12px;">(回车或移开输入框生成个汇聚口)</span></th> 
                        <th>操作</th> 
                    </thead>
                    <tbody>
                        <tr v-for="(item, index) in switchData" :key="index">
                            <td :class="{errInput : item.hostErr}"> 
                                <Input type="text" size="small" placeholder="请填写host" v-model="item.host" style="width: 110px; " />
                            </td>
                            <td>
                                <Input type="text" size="small" placeholder="请填写community" v-model="item.community" style="width: 110px; " />
                            </td>
                            <td>
                                <div style="width: 200px;">  
                                    <Select v-model="item.indexes" @on-open-change="(bool) => handleOpenIndexes(bool, item.host, item.community)" multiple style="width:200px">
                                        <Option v-for="item in switchIndexes[item.host]" :value="item.label + ':' + item.value" :key="item.value">{{ item.label }}(Index={{item.value}})</Option>
                                    </Select>
                                </div>
                            </td> 
                            <td>
                                <Button  
                                    size="small"
                                    type="text" 
                                    @click="insertRow(index)"
                                >插入</Button> 
                                <Button  
                                    v-show="index !== 0"
                                    size="small"
                                    type="text" 
                                    @click="deleteRow(index, item)"
                                >删除</Button>  
                            </td>
                        </tr>
                    </tbody>
                </table> 
            </div>   
          </div>
        <Button slot="footer" type="text" size="large" @click="handleCancel">取消</Button>
        <Button slot="footer" type="primary" size="large" @click="submit">确定</Button>
    </Modal> 
</template>

<script>
import { mapGetters } from 'vuex'
import { EMPTY_SWITCH_DATA } from '@/utils/opts'
import InputTag from 'vue-input-tag'
import { IP_RULE } from '@/utils/regExpRule'
import { cloneDeep } from '@/utils'
export default {
    name: "CreateDomainSwitch",
    computed: {
        ...mapGetters(['allCustomers', 'customerRelatedomains', 'switchIndexes'])
    },
    components: {
        InputTag,
    },
    props: {
        title: String,
        visible: Boolean,
        data: {
            type: Object,
            default(){
                return EMPTY_SWITCH_DATA
            }
        },
        isCreate: Boolean,
        domainName: String,
    },
    data(){
        return { 
            ruleValidate: {
                domain_id: [ 
                    { required: false, message: '请选择域名', trigger: 'change' }
                ]
            }, 
            temp: { 
                customer_id: '',
                domain_id: '',  
            },
            switchData: [
                this.renderDefaultswitch()
            ], 
            info: true 
        }
    },
    watch:{
        //监听外部数据变化
        data(d){
            let 
                _this = this,
                switchData = cloneDeep(d.switch);
            _this.temp.domain_id = `${d.domain_id}`  
            _this.switchData = switchData
            _this.info = true    
            //外部传入数据 获取汇聚口下拉
            switchData.map(item => {
                if(item.host && item.community)
                _this.$store.dispatch('querySwitchIndexes', {
                        host: item.host,
                        community : item.community
                })
            })
        },
        //客户变更
        ['temp.customer_id'](customer_id){ 
            let _this = this
            let condition = {
                params: customer_id ? {
                    customer_id
                } : {},
                cb(_data){ 
                    _this.temp.domain_id = '' 
                }
            }
            _this.$store.dispatch('fetchCustomerRelateDomain', condition);
        }
    },
    created(){
        //获取所有客户
        this.$store.dispatch('fetchAllCustomerList')
    },
    beforeDestroy(){
        console.log('beforeDestroy')
        // 清空汇聚口列表
        this.$store.commit('EMPTY_SWITCH_INDEXES')
    },
    methods: {
        submit(){ 
            this.info = true
            this.$refs.form.validate((valid) => {
                if (valid) { 
                    //交换机验证
                    /****** 不进行正则校验 has deleted ********/
                    // if(this.switchData.some(item => {  
                    //     return !item.host || !item.community   
                    // })){                            
                    //     this.$Message.warning("请检查交换机必填项是否未填");
                    //     this.info = false
                    //     return;  
                    // }  
                        
                    let 
                        checkPass = true ;
                    //检查填写项格式是否正确
                    this.switchData.forEach(item => { 
                        if(
                            !item.host || !item.community
                        ){  //必填项未填
                            checkPass = false
                        }

                        if(item.host && !IP_RULE.test(item.host)){
                            item.hostErr = true
                            checkPass = false
                        }else{
                            item.hostErr = false
                        }  
                    });  
                    if(!checkPass){               
                        this.$Message.warning("请检查交换机必填项是否填写正确");
                        this.info = false
                        return; 
                    }
                    
                    let switchData = this.switchData.map(item => {
                        return {
                            host: item.host,
                            community: item.community,
                            indexes: item.indexes, 
                        }
                    });
                    console.log(switchData);
                    this.$emit('save', Object.assign({}, {domain_id: parseInt(this.temp.domain_id)}, {switch : switchData})) 
                }
            })
        },
        handleOpenIndexes(bool, host, community){ 
            if(bool){ //打开下拉框 获取汇聚口列表 
                if(IP_RULE.test(host) && community){  //host 和 community已填写且格式正确，获取汇聚口列表
                    this.$store.dispatch('querySwitchIndexes', {
                        host,
                        community
                    })
                } 
            }
        },
        renderDefaultswitch(){
            return  { 
                host: "",
                community: "",
                indexes: []
            }
        },
        handleCancel(){
            this.$emit('closeModal')
        },
        deleteRow(index){  
            this.switchData.splice(index, 1)
        },
        insertRow(index){ 
            this.switchData.splice(index + 1, 0, this.renderDefaultswitch())
        },
    }
}
</script>

<style lang="scss"> 
.modalWrap{
    .title{
        border-left:  3px solid #409EFF;
        font-size: 16px;
        color: #333;
        padding-left: 10px;
        margin-bottom: 15px;
    }
    .modal-table{
        table{
            border-collapse: collapse;
            td, th{
                padding-left: 5px; 
            }
            tr{
                padding:  5px; 
            }
        }
    }
    .modal-table .vue-input-tag-wrapper .new-tag{
        max-width: 136px;
        padding: 0px;
    }
    .modal-table .vue-input-tag-wrapper .input-tag{
        background: #f3f3f3;
        border: none;
        color: #666;
        vertical-align: middle;
        .remove{
            color: #666;
            vertical-align: middle;
        }
    } 
    .errInput{ 
        .ivu-input{
            border: 1px solid red;
        }
    } 
}
</style>


